import config from '@/env/config.js'
// import zhHans from "./zh-Hans.json"
// import en from "./en.json"
// import zhHant from "./zh-Hant.json"
// 国际化
import { createI18n } from 'vue-i18n'// v9.x



// const messages = {
// 	en,
//     // 简体中文
// 	'zh-Hans': zhHans,
//     // 繁体中文
// 	'zh-Hant': zhHant
// }
let en = uni.getStorageSync('lang_en');
en = en ? JSON.parse(en) : undefined
let zhHans = uni.getStorageSync('lang_zhHans');
zhHans = zhHans ? JSON.parse(zhHans) : undefined
let zhHant = uni.getStorageSync('lang_zhHant');
zhHant = zhHant ? JSON.parse(zhHant) : undefined

let messages = {
  en: en || {
    common:{
      home:"首页",
      category:"分类",
      merchant:"商户",
      cart:"购物车",
      my_account:"我的"
    }
  },
  zhHans: zhHans || {
     common:{
      home:"首頁",
      category:"分類",
      merchant:"商戶",
      cart:"購物車",
      my_account:"我的"
    }
  },
  zhHant: zhHant || {
     common:{
      home:"Home",
      category:"Class",
      merchant:"Merchant",
      cart:"Cart",
      my_account:"My"
    }
  }

}

let i18nConfig = {
  locale:uni.getStorageSync('lang_locale')|| uni.getLocale(),// 获取已设置的语言
  messages,
  fallbackLocale: 'zh-Hans'
}

let i18n = createI18n(i18nConfig)
function getMessageValue(key, message) {
  const keys = key.split('.');
  const value = keys.reduce((obj, k) => (obj && obj[k] !== undefined) ? obj[k] : key, message);
  return value;
}
const oldT = i18n.global.t
let t = (key, place) => {
  let res = oldT(key, place)
  // let res = getMessageValue(key,i18n.global.messages[i18n.global.locale])
  if (place) {
    for (let key in place) {
      res = res.replace(new RegExp(`\\{\\s*${key}\\s*\\}`, 'g'), place[key])
    }
  }

  return res
}
i18n.global.t = t


function getMsg() {
  i18n.global.setLocaleMessage('en', messages.en)
  i18n.global.setLocaleMessage('zh-Hans', messages.zhHans)
  i18n.global.setLocaleMessage('zh-Hant', messages.zhHant)
  uni.request({
    url: config.app_url + '/api/resource/web_i18n/en.json', data: {}, header: { Accept: 'application/json', }, method: 'GET', success: ({ data, statusCode, header }) => {
      i18n.global.setLocaleMessage('en', data)
      uni.setStorageSync('lang_en',JSON.stringify(data))
    }
  })

   
  uni.request({
    url: config.app_url + '/api/resource/web_i18n/zh-Hans.json', data: {}, header: { Accept: 'application/json', }, method: 'GET', success: ({ data, statusCode, header }) => {
      i18n.global.setLocaleMessage('zh-Hans', data)
       uni.setStorageSync('lang_zhHans',JSON.stringify(data))
    }
  })
   
  uni.request({
    url: config.app_url + '/api/resource/web_i18n/zh-Hant.json', data: {}, header: { Accept: 'application/json', }, method: 'GET', success: ({ data, statusCode, header }) => {
      i18n.global.setLocaleMessage('zh-Hant', data)
      uni.setStorageSync('lang_zhHant',JSON.stringify(data))
    }
  })
}
getMsg()
export { i18nConfig, messages, t, i18n }